<template>
  <div class="full-interview-confirm-bg">
    <div class="full-interview-confirm-flex">
      <!-- 左侧介绍区块 -->
      <div class="intro-section card-offset-up">
        <div class="intro-title">全流程模拟面试前的准备</div>
        <div class="intro-desc">
          <p>欢迎体验 <span class="brand">AI智能全流程模拟面试</span>。</p>
          <ul>
            <li>请提前准备好安静的环境、良好的网络、麦克风和摄像头设备。</li>
            <li>检测通过后，您将体验从简历投递到Offer发放的完整面试流程。</li>
            <li>全流程模拟面试将帮助你提升真实面试表现，获得个性化反馈。</li>
          </ul>
          <div class="intro-tip">* 建议使用最新版 Chrome 浏览器获得最佳体验。</div>
        </div>
      </div>
      <!-- 右侧权限检测卡片 -->
      <div class="confirm-card card-offset-down">
        <div class="form-label">设备权限检测</div>
        <div class="device-check-list">
          <div class="device-check-item">
            <span class="device-icon">🎤</span>
            <span class="device-label">麦克风权限</span>
            <a-tag :color="micSuccess ? 'green' : 'orange'">
              {{ micSuccess ? '已就绪' : '未检测' }}
            </a-tag>
            <a-button type="primary" size="small" @click="checkMicrophone">检测麦克风</a-button>
          </div>
          <div class="device-check-item">
            <span class="device-icon">📷</span>
            <span class="device-label">摄像头权限</span>
            <a-tag :color="cameraStatus === 'ready' ? 'green' : 'orange'">
              {{ cameraStatus === 'ready' ? '已就绪' : '未检测' }}
            </a-tag>
            <a-button type="primary" size="small" @click="testCamera">测试摄像头</a-button>
          </div>
        </div>
        <div style="display: flex; gap: 16px; margin-top: 16px">
          <a-card v-if="cameraStatus === 'testing'" title="摄像头预览" style="flex: 1">
            <video
              ref="videoRef"
              autoplay
              playsinline
              style="width: 100%; height: 240px; border-radius: 8px"
            ></video>
            <canvas ref="canvasRef" style="display: none"></canvas>
            <div style="margin-top: 16px; text-align: center">
              <a-button type="primary" @click="takePhoto">拍照确认</a-button>
            </div>
          </a-card>
          <a-card v-if="photoData" title="照片确认" style="flex: 1" v-show="photoData">
            <img
              :src="photoData"
              style="width: 100%; height: 240px; object-fit: contain; border-radius: 8px"
            />
            <div style="margin-top: 16px; text-align: center">
              <a-button type="primary" style="margin-left: 8px" @click="retakePhoto"
                >重新拍照
              </a-button>
            </div>
          </a-card>
        </div>
        <a-button
          type="primary"
          size="large"
          class="main-btn"
          :disabled="!canStartInterview"
          @click="handleConfirm"
        >
          确认并开始面试
        </a-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import gsap from 'gsap'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useLoadingPage } from '@/utils/LoadingHelper'
import { generateFullProcessInterviewUsingGet } from '@/api/fullInterviewController'
import { removeLocalCache } from '@/utils/LocalStorageUtils'

const router = useRouter()
const micSuccess = ref(false)
const cameraSuccess = ref(false)
const micStatus = ref('')
const cameraStatus = ref('')
const photoData = ref('')
const videoRef = ref(null)
const canvasRef = ref(null)
const { withLoading } = useLoadingPage(router)

const checkMicrophone = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    stream.getTracks().forEach((track) => track.stop())
    micStatus.value = '麦克风权限检测成功'
    micSuccess.value = true
    message.success('麦克风测试成功！')
  } catch (error) {
    micStatus.value = '麦克风权限被拒绝，请检查浏览器设置'
    micSuccess.value = false
    message.error('麦克风访问被拒绝或不可用')
  }
}
const testCamera = async () => {
  message.info('正在请求摄像头权限，请稍候...')
  cameraStatus.value = 'testing'
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ video: true })
    const video = videoRef.value
    if (video) {
      video.srcObject = stream
      video.onloadedmetadata = () => video.play()
    }
  } catch (error) {
    cameraStatus.value = 'failed'
    message.error('摄像头访问被拒绝或不可用')
  }
}
const takePhoto = () => {
  const video = videoRef.value
  const canvas = canvasRef.value
  if (video && canvas) {
    canvas.width = video.videoWidth
    canvas.height = video.videoHeight
    const context = canvas.getContext('2d')
    context.drawImage(video, 0, 0, canvas.width, canvas.height)
    photoData.value = canvas.toDataURL('image/png')
    // 停止视频流
    const stream = video.srcObject
    if (stream) stream.getTracks().forEach((track) => track.stop())
    cameraStatus.value = 'ready'
    cameraSuccess.value = true
  }
}
const retakePhoto = () => {
  photoData.value = ''
  testCamera()
}
const canStartInterview = computed(() => {
  return micSuccess.value && cameraSuccess.value && photoData.value
})

/**
 * 开始全流程面试
 */
const handleConfirm = async () => {

  //删除全流程面试缓存
  removeLocalCache('currentStep')
  removeLocalCache('interviewInfo')
  removeLocalCache('fullInterviewId')

  if (!canStartInterview.value) {
    message.warning('请先完成麦克风和摄像头检测并拍照确认！')
    return
  }
  // 跳转到加载页面
  await withLoading(
    //发送请求生成技术面记录
    () => generateFullProcessInterviewUsingGet(),
    `/api/full/interview`, // 操作完成后跳转回当前页面
    '/',
    'full',
    false,
  )
}
onMounted(() => {
  nextTick(() => {
    gsap.from('.full-interview-confirm-bg', {
      opacity: 0,
      scale: 0.98,
      duration: 1,
      ease: 'power3.out',
    })
    gsap.from('.main-title', { opacity: 0, y: -40, duration: 1, delay: 0.1, ease: 'power2.out' })
    gsap.from('.confirm-card', {
      opacity: 0,
      y: 30,
      duration: 0.8,
      delay: 0.3,
      ease: 'back.out(1.7)',
    })
  })
})
</script>

<style scoped>
.full-interview-confirm-bg {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.full-interview-confirm-flex {
  width: 100%;
  max-width: 980px;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: center;
  gap: 36px;
  margin: 0 auto;
  padding: 48px 0 32px 0;
}

.intro-section {
  flex: 1.3;
  background: linear-gradient(135deg, #f8faff 0%, #ffffff 100%);
  border-radius: 20px;
  box-shadow: 0 16px 32px rgba(24, 144, 255, 0.08);
  padding: 48px 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 520px;
  max-width: 520px;
  border: 1px solid rgba(24, 144, 255, 0.1);
}

.card-offset-up {
  margin-top: -32px;
}

.card-offset-down {
  margin-top: 48px;
}

.intro-title {
  font-size: 2rem;
  font-weight: 800;
  color: #1890ff;
  margin-bottom: 24px;
  letter-spacing: 1.5px;
  position: relative;
  padding-bottom: 12px;
}

.intro-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 60px;
  height: 4px;
  background: linear-gradient(90deg, #1890ff 0%, #40a9ff 100%);
  border-radius: 2px;
}

.intro-desc {
  color: #333;
  font-size: 1.15rem;
  line-height: 2;
  font-weight: 400;
}

.intro-desc ul {
  margin: 18px 0 12px 18px;
  padding-left: 18px;
}

.intro-desc li {
  margin-bottom: 8px;
  font-size: 1.08rem;
}

.intro-tip {
  color: #faad14;
  font-size: 1.01rem;
  margin-top: 12px;
}

.brand {
  color: #1890ff;
  font-weight: 700;
  font-size: 1.08em;
}

.confirm-card {
  flex: 1.1;
  width: 100%;
  max-width: 520px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.05);
  padding: 40px 32px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  justify-content: center;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.form-label {
  font-size: 1.15rem;
  font-weight: 700;
  color: #333;
  margin-bottom: 16px;
}

.device-check-list {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 18px;
  margin-bottom: 16px;
}

.device-check-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  background: #f5f9ff;
  border-radius: 12px;
  padding: 12px 18px;
}

.device-icon {
  font-size: 1.3rem;
}

.device-label {
  font-size: 1.08rem;
  color: #1890ff;
  font-weight: 600;
}

.main-btn {
  width: 100%;
  height: 52px;
  font-size: 20px;
  font-weight: 700;
  border-radius: 18px;
  background: linear-gradient(135deg, #1890ff 80%, #40a9ff 100%);
  box-shadow: 0 4px 16px rgba(24, 144, 255, 0.12);
  border: none;
  transition: all 0.3s;
}

.main-btn:disabled {
  background: #e6e6e6;
  color: #aaa;
  box-shadow: none;
}

.main-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #40a9ff 80%, #1890ff 100%);
  box-shadow: 0 8px 32px rgba(24, 144, 255, 0.18);
}

@media (max-width: 980px) {
  .full-interview-confirm-flex {
    flex-direction: column;
    gap: 32px;
    padding: 24px 0 16px 0;
    align-items: center;
    max-width: 98vw;
  }

  .intro-section,
  .confirm-card {
    max-width: 98vw;
    padding: 24px 4vw 18px 4vw;
  }

  .card-offset-up,
  .card-offset-down {
    margin-top: 0;
  }
}

@media (max-width: 700px) {
  .intro-section,
  .confirm-card {
    padding: 14px 2vw 14px 2vw;
  }

  .intro-title {
    font-size: 1.2rem;
  }
}
</style>
